# @Time : 2020/8/31 14:12
# @Author : Fioman 
# @Phone : 13149920693
"""

"""
import cv2 as cv
import imutils
import numpy as np


def sort_contours(cnts, method="left-to-right"):
    reverse = False
    i = 0

    # 当我们需要反向的时候
    if method == "right-to-left" or method == "bottom-to-top":
        reverse = True

    if method == "top-to-bottom" or method == "bottom-to-top":
        i = 1

    boundingBoxes = [cv.boundingRect(c) for c in cnts]
    cnts, boundingBoxes = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b: b[1][i], reverse=reverse))

    return cnts, boundingBoxes


def draw_contour(image, c, i):
    M = cv.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])
    cv.putText(image, "#{}".format(i + 1), (cX - 20, cY), cv.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2)

    return image


if __name__ == '__main__':
    image = cv.imread("pic/25.png")
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    accumEdged = np.zeros(image.shape[:2], dtype=np.uint8)

    for chan in cv.split(image):
        chan = cv.medianBlur(chan, 11)
        edged = cv.Canny(chan, 50, 200)
        accumEdged = cv.bitwise_or(accumEdged, edged)

    cv.imshow("Edge Map", accumEdged)
    cv.waitKey(0)

    cnts = cv.findContours(accumEdged.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    cnts = sorted(cnts, key=cv.contourArea, reverse=True)[:5]
    orig = image.copy()

    for index, c in enumerate(cnts):
        orig = draw_contour(orig, c, index)

    cv.imshow("Unsorted", orig)

    cnts, boundingBoxes = sort_contours(cnts, method="left-to-right")

    for index, c in enumerate(cnts):
        draw_contour(image, c, index)

    cv.imshow("Sorted", image)
    cv.waitKey(0)
